package com.gk.controller;

import com.gk.feignclients.ProductClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class UsrController {

    private static final Logger log = LoggerFactory.getLogger(UsrController.class);

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient; //负载均衡客户端组件

    @Autowired
    private RestTemplate restTemplate; //注入进来的RestTemplate具有负载均衡功能

    @Autowired
    private ProductClient productClient;

    @GetMapping("/invoke")
    public String invokeProduct() {
        log.info("调用商品服务...");

        //调用商品服务，缺点：1、无法实现请求负载均衡 2、路径写死代码中，不利于后续维护
        //String result = new RestTemplate().getForObject("http://localhost:9090/product?id=1", String.class);

        //1.discoveryClient使用ribbon组件实现负载均衡 1.引入ribbon（nacos client 存在这个依赖) 2.使用ribbon完成负载均衡
        /*
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("PRODUCTS");
        for (ServiceInstance serviceInstance : serviceInstances) {
            log.info("服务主机：{}，服务端口：{}，服务uri：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
        }
        */
        //2. loadBalancerClient
        //ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCTS"); //返回的节点已经进行负载均衡了， 采用的是轮询策略
        //String result = new RestTemplate().getForObject(serviceInstance.getUri() + "/product?id=1", String.class);

        //3.@LoadBalance注解
        //String result = this.restTemplate.getForObject("http://PRODUCTS:9090/product?id=1", String.class);

        String result = productClient.product(21);

        return result;
    }
}
